#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <fstream>
#include <sstream>

#include "logger.hpp"

using namespace rsv;

class ProducerConsumer {
private:
    std::queue<std::pair<double, double>> dataQueue;
    std::mutex mtx;
    std::condition_variable cv_producer, cv_consumer;
    std::vector<std::thread> producers;
    std::vector<std::thread> consumers;

public:
    void producer() {
        for (int i = 0; i < 5; ++i) {
            std::unique_lock<std::mutex> lock(mtx);
            cv_producer.wait(lock, [&] { return dataQueue.size() < 10; });  // 等待队列不满
            dataQueue.push(std::make_pair(i, i + 1));
            cv_consumer.notify_all();  // 唤醒等待的消费者线程
        }
    }

    void consumer() {
        for (int i = 0; i < 5; ++i) {
            std::pair<double, double> data;
            {
                std::unique_lock<std::mutex> lock(mtx);
                cv_consumer.wait(lock, [&] { return !dataQueue.empty(); });  // 等待队列非空
                data = dataQueue.front();
                dataQueue.pop();
                cv_producer.notify_all();  // 唤醒等待的生产者线程
            }
            double result = (data.first * 10 + data.second * 10);
            LOG(Logger::Level::INFO, std::to_string(result));
        }
    }

    size_t getQueueSize() {
        std::lock_guard<std::mutex> lock(mtx);
        return dataQueue.size();
    }

public:
    void run() {
        for (int i = 0; i < 2; ++i) {
            producers.push_back(std::thread(&ProducerConsumer::producer, this));
        }
        
        for (int i = 0; i < 2; ++i) {
            consumers.push_back(std::thread(&ProducerConsumer::consumer, this));
        }

        for (auto& t : producers) {
            t.join();
        }

        for (auto& t : consumers) {
            t.join();
        }
    }
};

